import axios from "axios";
import nProgress from "nprogress";
import 'nprogress/nprogress.css'
import store from "@/store";

// 创建一个axios实例
const request = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 10000
})

// 设置请求拦截器
request.interceptors.request.use(
  (config) => {
    nProgress.start()
    // 发送请求时请求头携带userTempId
    const userTempId = store.state.user.userTempId
    config.headers.userTempId = userTempId
    // 发送请求时请求头携带token
    const token = store.state.user.token
    config.headers.token = token
    return config
  },
  (error) => {
    nProgress.done()
    return Promise.reject(error.message)
  }
)

// 设置响应拦截器
request.interceptors.response.use(
  (response) => {
    nProgress.done()
    if (response.data.code === 200) {
      return response.data.data
    } else {
      return Promise.reject({ message: response.data.message })
    }
  },
  (error) => {
    nProgress.done()
    return Promise.reject(error.message)
  }
)

export default request